package com.ugrow.ugrowcommunity.activity.posttrend;



import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProviders;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionSelectedListener;
import com.ugrow.ugrowcommunity.BuildConfig;
import com.ugrow.ugrowcommunity.R;
import com.ugrow.ugrowcommunity.data.Data;

import com.ugrow.ugrowcommunity.databinding.ActivityPostTrendBinding;
import com.ugrow.ugrowcommunity.util.HttpUtil;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;


public class PostTrendActivity extends AppCompatActivity implements OnOptionPickedListener {

    private ActivityPostTrendBinding binding;
    private PostTrendViewModel mViewModel;
    private String picturePath;
    private Boolean onClickLabel = false,onClickPrivacy = false;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(Color.rgb(91,111,227));
        binding = ActivityPostTrendBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        onClick();
        initView();


    }


    private void initView(){
        mViewModel = ViewModelProviders.of(this).get(PostTrendViewModel.class);
        //设置用户头像
        Glide.with(this).load(Data.StudentBean.getData().get(0).getStuPhoto()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.imgAvatar);
        binding.tvName.setText(Data.StudentBean.getData().get(0).getStuName());
    }

    private void onClick(){
        //设置文章发表监听
        binding.btPosttrend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = binding.etContent.getText().toString();
                String label = binding.tvLabel.getText().toString();
                if("添加标签".equals(label)){
                    label="英谷日常";
                }
                postTrend(picturePath,content,Integer.valueOf(Data.ID),label);
            }
        });

        //设置返回监听
        binding.ACback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        //设置添加图片监听
        binding.addimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求权限
                initPermissions();
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });

        //设置添加标签监听
        binding.tvLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] labels = {"专业前景", "旅行", "四季美景", "英谷日常", "爱情", "酸柠檬", "养宠物", "体育运动", "校园八卦", "失物招领", "美食"};
                String title = "文章标签选择";

                onClickLabel = true;
                onOptionText(labels,title);


            }
        });

        //设置访问权限
        binding.tvPrivacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] labels = {"公开","仅同学","仅老师","仅组群","仅好友"};
                String title = "访问权限设置";
                onClickPrivacy = true;
                onOptionText(labels,title);
            }
        });


    }


    //文章发表
    private void postTrend(String imagePath,String content,int  authorId,String label){
        HashMap<String, Object> map = new HashMap<>();
        if(imagePath == null){
            Toast.makeText(PostTrendActivity.this,"请选择一张图片",Toast.LENGTH_SHORT).show();
        }else {
            map.put("files",new File(imagePath));
            map.put("content",content);
            map.put("authorId",authorId);
            map.put("title",label);

            HttpUtil.httpPost(BuildConfig.ARTICLES_SAVE, map, HttpUtil.ContentType.IMAGE, new HttpUtil.CallBack() {
                @Override
                public void success(HttpUtil.Result result) {
                    Toast.makeText(PostTrendActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void failed(IOException e) {
                    Toast.makeText(PostTrendActivity.this, "发表失败，请检查网络连接！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 请求权限
     */
    private void initPermissions() {
        mViewModel.permissionsList.clear();

        //判断哪些权限未授予
        for (String permission : mViewModel.permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                mViewModel.permissionsList.add(permission);
            }
        }

        //请求权限
        if (!mViewModel.permissionsList.isEmpty()) {
            String[] permissions = mViewModel.permissionsList.toArray(new String[0]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
    }

    //图片显示回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (!picturePath.isEmpty()) {
                Bitmap articleImg = BitmapFactory.decodeFile(picturePath);
                binding.addimg.setImageBitmap(articleImg);
            }
        }
    }


    //标签选择器
    public void onOptionText(String[] strings,String title) {
        DialogConfig.setDialogStyle(DialogStyle.Three);//设置弹窗类型为从中间开始
        OptionPicker picker = new OptionPicker(this);
        picker.setData(Arrays.asList(strings));
        picker.setOnOptionPickedListener(PostTrendActivity.this);
        picker.setTitle(title);
        picker.getWheelLayout().setOnOptionSelectedListener(new OnOptionSelectedListener() {
            @Override
            public void onOptionSelected(int position, Object item) {
                //实时回调
            }
        });
        picker.getWheelView().setStyle(R.style.WheelDefault);
        picker.show();
    }



    @Override
    public void onOptionPicked(int position, Object item) {
        if(onClickLabel){
            binding.tvLabel.setText((String)item);
        }
       if(onClickPrivacy){
           binding.tvPrivacy.setText((String)item);
       }
        onClickLabel = false;
        onClickPrivacy = false;
    }


    //BitmapFactory.decodeFile()
}